package br.edu.fapi.gestao.pg.controlador;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

@ManagedBean
@SessionScoped
public class FileUploadControle {
	
	private List<UploadedFile> uploadedFileList;
	
	private String valorCurso;
	
	private String valorConvenio;
	
	private String valorTelessala;
	
	private FacesContext context;
	
	public FileUploadControle(){
		uploadedFileList = new ArrayList<UploadedFile>();
		context = FacesContext.getCurrentInstance();
		valorCurso = (String) context.getExternalContext().getRequestMap().get("curso");
		valorConvenio = (String) context.getExternalContext().getRequestMap().get("convenio");
		valorTelessala = (String) context.getExternalContext().getRequestMap().get("telessala");
		System.out.println(valorCurso + valorConvenio + valorTelessala);
	}
	
	public void handleFileUpload(FileUploadEvent event) {  
        FacesMessage msg = new FacesMessage("OK", event.getFile().getFileName() + " deu certo.");  
        FacesContext.getCurrentInstance().addMessage(null, msg);
        uploadedFileList.add(event.getFile());
    }
	
	public void saveFileList() throws Exception{
		File tempfile2 = new File("c:\\arquivos.zip");
		FileOutputStream output2 = new FileOutputStream(tempfile2);
		ZipOutputStream zipoutput = new ZipOutputStream(output2);

		for(UploadedFile file : uploadedFileList){
			//File tempfile = new File("c:\\"+file.getFileName());
			//FileOutputStream output = new FileOutputStream(tempfile);
			zipoutput.putNextEntry(new ZipEntry(file.getFileName()));
			zipoutput.write(file.getContents());
		}
		zipoutput.flush();
		zipoutput.close();
		uploadedFileList.clear();
	}
}
